<?php
namespace Foxframe;

class FileUpload
{
	public static $configuracao;

	public static function init()
	{
		self::$configuracao	= Registry::getInstance()->get('entityManager')->getRepository('\Entities\Corp\Configuracao')->find(1);
	}

	public static function upload($file, $indice = null)
	{
		try
		{
			if (!is_null($indice))
			{
				$tmp_name	= $file['tmp_name'][$indice];
				$name		= $file['name'][$indice];
			}
			else
			{
				$tmp_name	= $file['tmp_name'];
				$name		= $file['name'];
			}


			$ano		= date('Y');
			$mes		= date('m');
			$directory	= $ano.'/'.$mes;

			$remote_file	= time().rand(1000,9999);
			$local_file		= $tmp_name;

			self::init();

			$ftp	= ftp_connect(self::$configuracao->getFtpHost(), self::$configuracao->getFtpPorta());
			ftp_login($ftp, self::$configuracao->getFtpUsuario(), self::$configuracao->getFtpSenha());

			@ftp_mkdir($ftp, $ano);
			@ftp_mkdir($ftp, $ano.'/'.$mes);
			ftp_chdir($ftp, $directory);


			$extensao	= explode('.', $name);
			$extensao	= $extensao[count($extensao) -1];
			$em			= Registry::getInstance()->get('entityManager');
			$idpessoa	= unserialize($_SESSION[SESSION_LOGIN]['usuario'])->getIdPessoa();
			$pessoa		= $em->getRepository('\Entities\Corp\Pessoa')->find($idpessoa);

			$arquivo	= new \Entities\Corp\Arquivo();
			$arquivo->setDsNome($name);
			$arquivo->setDsPath($remote_file);
			$arquivo->setDsExtensao($extensao);
			$arquivo->setPessoa($pessoa);

			if (!ftp_put($ftp, $remote_file, $local_file, FTP_BINARY))
				throw new \Exception('Erro ao enviar arquivo');

			ftp_close($ftp);


			$em->persist($arquivo);
			$em->flush();

			return $arquivo;
		}
		catch (Exception $e)
		{
			throw new Exception($e->getMessage());
		}
	}

	public static function download($idarquivo)
	{
		$arquivo	= Registry::getInstance()->get('entityManager')->getRepository('\Entities\Corp\Arquivo')->find($idarquivo);
		$nome		= $arquivo->getDsNome();
		$ano		= $arquivo->getDtCadastro()->format('Y');
		$mes		= $arquivo->getDtCadastro()->format('m');
		$directory	= $ano.'/'.$mes;

		self::init();
		$ftp	= ftp_connect(self::$configuracao->getFtpHost(), self::$configuracao->getFtpPorta());
		ftp_login($ftp, self::$configuracao->getFtpUsuario(), self::$configuracao->getFtpSenha());

		ftp_chdir($ftp, $directory);

		ftp_get($ftp, 'tmp/'.$arquivo->getDsPath(), $arquivo->getDsPath(), FTP_BINARY);

		while (!is_file('tmp/'.$arquivo->getDsPath()))
			sleep(1);

		$content	= self::getFileContent('tmp/'.$arquivo->getDsPath());
		@unlink('tmp/'.$arquivo->getDsPath());

		header('Content-Description: File Transfer');
		header("Content-Disposition: attachment; filename=\"$nome\"");
		header('Content-Transfer-Encoding: binary');
		header("Accept-Ranges: bytes");
		header('Expires: 0');
		header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		header("Pragma: no-cache");

		echo $content;
		exit();
	}

	public static function getFileContent($path)
	{
		return file_get_contents($path);
	}
}